<!--
  富文本编辑器使用示例：
  <MyEditor :content="dialogForm.description" @update="updateFullText" />

  // 更新富文本编辑器内容
  const updateFullText = (content) => {
    if (dialogVisible.value) {
      dialogForm.description = content
    } else {
      form.description = content
    }
  }

  文件上传使用示例：
  <el-upload
            :action="uploadPath"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccessAdd"
            :on-error="handleAvatarErrorAdd"
            :headers="{ Authorization: getStorage('TOKEN') }"
          >
            <el-avatar size="large" :src="form.avatar" />
   </el-upload>
   import { getStorage } from '@/utils/storage.js'
   // 上传图片接口地址
   const BASE_URL = import.meta.env.VITE_BASE_API
   const uploadPath = BASE_URL + '/common/upload'

   // 上传文件前的校验
   const beforeUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        ElMessage.error('上传文件只能是图片!')
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    }

    // 上传图片成功后的回调
    const handleAvatarSuccessAdd = (res, file) => {
      if (dialogVisible.value) {
        dialogForm.image = file.response.data
      } else {
        form.image = file.response.data
      }
    }

    // 上传图片失败后的回调
    const handleAvatarErrorAdd = (err, file) => {
      if (err.toString().indexOf('401')) {
        ElMessage.error('请先登录!')
        router.push('/login')
      } else {
        ElMessage.error(err)
      }
    }
-->

<template>
  <div style="border: 1px solid #ccc;height: 260px;overflow: auto">
    <Toolbar
      v-if="showToolbarFlag"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
      :style="{ height: editorHeight, overflowY: 'hidden' }"
      :readOnly="readOnlyFlag"
    />
  </div>
</template>

<script setup lang="ts">
import { watch, onBeforeUnmount, nextTick, ref, shallowRef, onMounted, onBeforeMount } from 'vue'
//@ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { getStorage } from "@/utils/storage.js";


// Props：使用属性，子组件接收父组件传递的内容
const props = defineProps({
  // 内容
  content: { type: String, default: '' },
  // 工具栏是否显示，默认显示
  showToolbarFlag: { type: Boolean, default: true },
  // 编辑器高度，默认500px
  editorHeight: { type: String, default: '500px' },
  // 编辑器是否只读，默认可编辑
  readOnlyFlag: { type: Boolean, default: false }
})

// Emits：使用事件，将子组件内容传递给父组件。父组件使用 update(content: string)
const emit = defineEmits<{ (e: 'update', content: string): void }>()

const mode = ref('default')

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')

const toolbarConfig = {}

const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {} as any
}

const BASE_URL = import.meta.env.VITE_BASE_API

// 上传图片配置
editorConfig.MENU_CONF['uploadImage'] = {
  // form-data fieldName ，默认值 'wangeditor-uploaded-image'。传给后端接口的参数名，重要!
  fieldName: 'file',
  server: BASE_URL + `/common/upload`,
  headers: {
    Authorization: getStorage("TOKEN"),
  },
  customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
    console.log("res", res)
    const url = res.data
    const alt = "图片"
    const href = url
    // 从 res 中找到 url alt href ，然后插入图片
    insertFn(url, alt, href)
  },
}

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！

  // 根据父组件传递的readOnlyFlag，设置编辑器为只读
  if (props.readOnlyFlag) {
    editorRef.value.disable()
  } else {
    editorRef.value.enable()
  }
}

const handleChange = () => {
  valueHtml.value = editorRef.value.getHtml()
  emit('update', valueHtml.value)
}

// 监听 props 变化，监听父组件传来的content
watch(() => props.content, (newVal: string) => {
    nextTick(() => {
      if (editorRef.value) {
        // console.log(" 当前编辑器的状态：", editorRef.value);

        // 富文本编辑器按 html 格式回显
        editorRef.value.setHtml(newVal)
        valueHtml.value = newVal
      }
    })
  }
)

onMounted(async () => {
  await nextTick() // 延迟渲染，确保 DOM 更新完成
  if (props.content) {
    valueHtml.value = props.content
  }
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

</script>
